//
//  AddressBookViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14-10-9.
//  Copyright (c) 2014年 科创. All rights reserved.
//
#define ADD_GROUP_ALERT_TAG  1012
#define CREAT_GROUP_ALERT_TAG  1013


#import "AddressBookViewController.h"
#import "AddressBookTableViewCell.h"
#import "AddFriendViewController.h"
#import "ContactDao.h"

@interface AddressBookViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    BOOL isFirstInitRightController;
    UISearchDisplayController *searchDisplayController;
    NSString * title;
    NSMutableDictionary *keyCountMap;
    Contact *curOrgContact;
    NSArray * keySortList;
    long childSize;
    int passOrgChildCount;
    

}
@property (strong, nonatomic) UISearchBar * searchBar;

@end

@implementation AddressBookViewController

@synthesize index,rightBtn,isCreatGroup,passOrgContact,selectedContact;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    
    return self;
}

-(void) onGroupClikc:(NSString*)groupId{
    
    //NSLog(@"-------groupId=%@",groupId);
    curOrgContact =[ContactDao getContactById:groupId];
    self.lableTitle.text =curOrgContact.mNAME;
    
    if (!isCreatGroup) {
        if ([curOrgContact.mID hasPrefix:@"friend_"]) {
            [rightBtn setTitle:@"添加好友" forState:UIControlStateNormal];
            rightBtn.frame = CGRectMake(SCREEN_WIDTH-90, (YNEW)+5, 80.0f, 30.0f);
        }else
        {
            [rightBtn setTitle:@"群聊" forState:UIControlStateNormal];
            rightBtn.frame = CGRectMake(SCREEN_WIDTH-50, (YNEW)+5, 40.0f, 30.0f);
            
        }
    }
    
    [self resortContactList:@""];
    [_addressTableview reloadData];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
   

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    curOrgContact =[ContactDao getContactById:[DE getGlobalVar:LOGIN_USER_ORGID]];
    
    [self addTitleBarWithBackBtn:curOrgContact.mNAME];
    //联系人列表
    _addressTableview.tableHeaderView.backgroundColor = [UIColor whiteColor];
    int tableHeinght= isCreatGroup?(self.view.frame.size.height-TITLE_BAR_HEGIHT-TABBARHEIGHT-(YNEW)):(self.view.frame.size.height-TITLE_BAR_HEGIHT-44-TABBARHEIGHT-(YNEW));
    _addressTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW)+44, SCREEN_WIDTH, tableHeinght) style:UITableViewStylePlain];
    _addressTableview.delegate = self;
    _addressTableview.dataSource = self;
    _addressTableview.bounces=NO;
     _addressTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_addressTableview];
    //搜索框
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, 44)];
    _searchBar.showsCancelButton=NO;
    _searchBar.barStyle=UIBarStyleDefault;
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    [self.view addSubview:_searchBar];
    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.searchResultsTableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(10.0f, (YNEW)+7, isCreatGroup?65.0f:40.0f, 30.0f);
    [leftBtn addTarget:self action:@selector(addressbookShowLeftView:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setBackgroundImage:[[UIImage imageNamed:@"btntop_right_over"]stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateNormal];
    [leftBtn setBackgroundImage:[[UIImage imageNamed:@"btntop_right_over_press"]stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateHighlighted];
    [leftBtn setTitle:isCreatGroup?@"切换群组":@"群组" forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.titlebar addSubview:leftBtn];
    
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setBackgroundImage:[[UIImage imageNamed:@"btntop_right_over"]stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateNormal];
    [rightBtn setBackgroundImage:[[UIImage imageNamed:@"btntop_right_over_press"]stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateHighlighted];
    [rightBtn setTitle:isCreatGroup?@"取消":@"群聊" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(SCREEN_WIDTH-50,(YNEW)+7, 40.0f, 30.0f);
    [rightBtn addTarget:self action:@selector(addressbookShowRightView:) forControlEvents:UIControlEventTouchDown];
    [self.titlebar addSubview:rightBtn];

    AddressBookLeftViewController *left =nil;
    if(isCreatGroup){
        left = (AddressBookLeftViewController*)self.drawer.leftViewController;
        selectedContact = [[NSMutableSet alloc] init];
        
        if (passOrgContact) {
            passOrgChildCount = [ContactDao queryChildCount:passOrgContact.mID];
        }
        
    }else{
        //主界面只有再点击通讯录的时候才会完成抽屉的创建，所以通过self.drawer获取的left为nil
        left = (AddressBookLeftViewController*)kAppDelegate.iCSDrawerController.leftViewController;
    }
    left.groupdelegate = self;
    
     [self resortContactList:@""];

    
    [self setExtraCellLineHidden:_addressTableview];
 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
-(void)addressbookShowLeftView:(id)sender
{
    if (isCreatGroup) {
        [self.drawer open];
    }else{
        [kAppDelegate.iCSDrawerController open];
    }
}

-(void)addressbookShowRightView:(id)sender
{
 
    if(isCreatGroup){
        if (passOrgContact && selectedContact.count>0) {
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"确定添加人员?" message:nil delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"确认", nil];
            view.tag = ADD_GROUP_ALERT_TAG;
            [view show];
            
        }else if (selectedContact.count>=2) {
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"确定创建群组?" message:nil delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"确认", nil];
            view.tag = CREAT_GROUP_ALERT_TAG;
            [view show];
            
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
        return;
    }
    if (childSize>99) {
        [self showAlerHUD:@"群组人员太多（最多支持100人群），暂不支持群发功能！"];
        return;
    }
    
    if ([curOrgContact.mID hasPrefix:@"friend_"]) {
        AddFriendViewController * addfriend = [[AddFriendViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:addfriend animated:NO];

    }else
    {
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":curOrgContact.mPK_ID,
                               @"recordID":curOrgContact.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString * identifier = @"AddressBookTableViewCell";
    AddressBookTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[AddressBookTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    NSString *key = [keySortList objectAtIndex:indexPath.section];
    NSArray *aray = [keyCountMap objectForKey:key];
    Contact *contact =[aray objectAtIndex:indexPath.row];
    
    [cell setContactValue:contact isCreat:isCreatGroup ];
    [cell setContactSelected:[selectedContact containsObject:contact.mID]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CONTACT_HEIGHT;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    NSString *key = [keySortList objectAtIndex:indexPath.section];
    NSArray *aray = [keyCountMap objectForKey:key];
    Contact *contact =[aray objectAtIndex:indexPath.row];
    if (!isCreatGroup) {
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"2",@"record_DB_ID":contact.mPK_ID,
                               @"recordID":contact.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];

    }else{
        if (![selectedContact containsObject:contact.mID]) {
            [selectedContact addObject:contact.mID];
        }else{
            [selectedContact removeObject:contact.mID];
        }
         NSArray *indexArray=[NSArray arrayWithObject:indexPath];
        [_addressTableview reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if (passOrgContact && selectedContact.count>0 && (passOrgChildCount+selectedContact.count)<100) {
            rightBtn.titleLabel.text=@"完成";
        }else if (selectedContact.count>=2 && selectedContact.count<100) {
            rightBtn.titleLabel.text=@"完成";
        }
        else{
            rightBtn.titleLabel.text=@"取消";
         }

    }
    
}

//右边显示的内容字母
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return keySortList;
}

//section的证书
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return keySortList.count;
}

//每一个section的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [keySortList objectAtIndex:section];
    NSArray *aray = [keyCountMap objectForKey:key];
    return aray.count;
}

-(void)addGroupMember{
    
    NSEnumerator *enumerator = [selectedContact objectEnumerator];
    [selectedContact addObject:DE.userId];
    NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
    for (NSObject *cid in enumerator) {
        [ids insertString:[NSString stringWithFormat:@"%@,",cid] atIndex:0];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"addGrpMember" params:@{@"userIds":ids,@"groupId":passOrgContact.mID} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];

        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加群成员成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                        [view show];
                        
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"添加群成员失败！"];
                    }
                }else{
                    [self showAlerHUD:@"添加群成员失败！"];
                }
            }];
            
        }else{
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加群成员失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
            [view show];
        }
        
    }];
    
}

-(void)createGruoup{
    
    NSEnumerator *enumerator = [selectedContact objectEnumerator];
    [selectedContact addObject:DE.userId];
    NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
    for (NSObject *cid in enumerator) {
        [ids insertString:[NSString stringWithFormat:@"%@,",cid] atIndex:0];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"createGrp" params:@{@"userIds":ids} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (success) {
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};

            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                        [view show];

                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"创建群组失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"创建群组失败！"];

                }
                
            }];
            
        }else{
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
            [view show];
        }
        
    }];
    
}



-(void)reloadContactWhenChanger{
    
    if (!isCreatGroup) {
        [self onGroupClikc:[DE getGlobalVar:LOGIN_USER_ORGID]];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
         if (alertView.tag == CREAT_GROUP_ALERT_TAG) {
            [self createGruoup];
         }else  if (alertView.tag == ADD_GROUP_ALERT_TAG){
            [self addGroupMember];
         }
        
    }
}

 // called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [self resortContactList:searchText];
    [_addressTableview reloadData];


}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self resortContactList:@""];
    [_addressTableview reloadData];
}

-(void)resortContactList:(NSString*)key{
    
    NSArray * orgContactList = [ContactDao searcherNodeContact:curOrgContact.mID key:key];
    
 
   orgContactList= [orgContactList sortedArrayUsingComparator:^NSComparisonResult(Contact *p1, Contact *p2){
        
        return [p1.mQP compare:p2.mQP];
             
    }];
    
    childSize = orgContactList.count;
    keyCountMap = [[NSMutableDictionary alloc] init];
    
    bool isshow = [@"OFF" isEqualToString:[DE getGlobalVar:IS_SHOW_UNACTIVE_USER]];
    for (int i=0; i<orgContactList.count; i++) {
  
        Contact*contact =[orgContactList objectAtIndex:i];
        
        if (isshow)
        {
            if ([contact.mHEAD_IMG hasSuffix:@"defaultheadimg.png"]) {
                continue;
            }
        }
        NSString *key = [contact.mQP.length>=1?contact.mQP:@"#" substringToIndex:1];
        if ([keyCountMap objectForKey:key]) {
            NSMutableArray *array = [keyCountMap objectForKey:key];
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }else{
            NSMutableArray *array = [[NSMutableArray alloc] init] ;
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }

    }
    
    keySortList =[keyCountMap allKeys];
    keySortList = [keySortList sortedArrayUsingComparator:^NSComparisonResult(NSString *p1, NSString *p2){
        return [p1 compare:p2];
    }];    
}

@end
